package register

import (
	"fmt"
	"gitee.com/zaper/patch/constant"
	"gitee.com/zaper/patch/router"
	"gitee.com/zaper/patch/util"
	"gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center-client/global_sign"
	util2 "gitee.com/zaper/service-center-client/util"
	"github.com/gin-gonic/gin"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/transport/http"
)

var (
	RouteCount = 0
)

func InitializeRoute() {
	go func() {
		startTime := util.GetCurrentTimeStamp()
		logger.Infof("Begin async init router.")
		gWeb := gin.New()
		gWeb.Use(router.GetHttpMiddleWare()...)
		for _, gp := range router.Groups {
			group := gWeb.Group(gp)
			for _, route := range router.GetRoute() {
				if gp == route.Group {
					RouteCount++
					switch route.FuncType {
					case constant.HttpGET:
						group.GET(route.Url, route.Func...)
					case constant.HttpPOST:
						group.POST(route.Url, route.Func...)
					case constant.HttpPUT:
						group.PUT(route.Url, route.Func...)
					case constant.HttpDELETE:
						group.DELETE(route.Url, route.Func...)
					}
					logger.Printf("%d routes have been initialized.", RouteCount)
				}
			}
		}
		err := registerGinToKts(gWeb).Run()
		if err != nil {
			return
		}
		logger.Infof("End async init router success, cost time %d ms", util.GetCurrentTimeStamp()-startTime)
	}()
}

func registerGinToKts(engine *gin.Engine) *kratos.App {
	port := util2.GetListenPort()
	global_sign.PortChan <- port
	httpSrv := http.NewServer(http.Address(fmt.Sprintf(":%s", port)))
	httpSrv.HandlePrefix("/", engine)
	return kratos.New(
		kratos.Server(httpSrv),
	)
}
